<?php
namespace Admin\Model;

class AdminModel extends CommonModel{
	protected $_fields = ["username","password","is_open"];
	protected $_validate = [
		["username","require","角色名称必填"],
		['username','','帐号名称已经存在！',0,'unique'],
		["password","require","密码必填"],
	];
	//自动完成
	protected $_auto = [
		['password','md5',3,'function'],
	];

	public function _after_insert($data){
		//插入中间表 角色权限表 shop_admin_role
		$admin_role = [
			"admin_id" => $data["id"],
			"role_id" => intval(I("post.role_id")),
		];
		M("AdminRole")->add($admin_role);
	}
	public function listData(){
		//获取用户表,角色表以及中间表
		//页面尺寸
		$pageSzie = 10;
		$count = $this->count();
		$page = new \Think\Page($count,$pageSzie);
		$show = $page->show();
		$list = $this->where("is_open=1")->alias("a")->field("a.*,r.role_name")->join("left join shop_admin_role ar on a.id=ar.admin_id")->join("left join shop_role r on ar.role_id=r.id")->page($page->firstRow.",".$pageSzie)->select();
		return ["pageStr"=>$show,"list"=>$list];
	}
	public function dels($id){
		//删除用户信息 删除角色信息 使用事务
		$this->startTrans();
		//删除用户信息
		$admin_status = $this->where("id=".$id)->delete();
		if($admin_status === false){
			$this->rollback();
			return false;
		}
		//删除角色信息
		$role_status =M("AdminRole")->where("admin_id=".$id)->delete();
		if($role_status === false){
			$this->rollback();
			return false;
		}
		$this->commit();
		return true;                 
	}

	public function findOne($id){
		//获取用户表以及对应的角色ID
		$list = $this->alias("a")->field("a.*,ar.role_id")->join("left join shop_admin_role ar on a.id=ar.admin_id")->where("a.id=".$id)->find();
		return $list;
	}

	public function update($data){
		//修改角色以及对应中间表
		$role_id = intval(I("post.role_id"));
		if($role_id <= 1){
			$this->error("参数错误");
		}
		//修改角色
		$this->save($data);
		//修改对应中间表
		M("AdminRole")->where("admin_id=".$data["id"])->save(["role_id"=>$role_id]);
	}

	//登录验证
	public function login($username,$password){
		$userinfo = $this->where("username='$username'")->find();
		if(!$userinfo){
			$this->error = "账号不存在";
			return false;
		}
		//根据密码进行对比
		if($userinfo["password"] != md5($password)){
			$this->error = "密码错误";
			return false;
		}
		//记录登录状态
		cookie("admin",$userinfo);
		return true;
	}
}